<template>
  <el-dialog
    title="执行任务"
    :visible.sync="dialogExcuteTaskVisibleInChild"
    fullscreen
  >
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane
        v-if="generateTaskFormVisible"
        name="taskForm"
        label="任务表单"
      >
        <fm-generate-form
          ref="generateFormTask"
          :data="taskFormJson"
          :value="taskFormData"
        />
      </el-tab-pane>
      <el-tab-pane name="processInstanceForm" label="流程表单(只读)">
        <fm-generate-form
          v-if="generateStartFormVisible"
          ref="generateFormStart"
          :data="startFormJson"
          :value="processInstanceFormData"
        />
        <el-form v-if="showBusinessKey" label-width="100px">
          <el-form-item label="业务主键Key:">
            <el-input v-model="businessKey" disabled />
          </el-form-item>
        </el-form>
        <div v-if="!generateStartFormVisible && !showBusinessKey">无</div>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-form label-width="100px">
        <el-form-item label="意见:">
          <el-input
            v-model="message"
            :autosize="{ minRows: 2, maxRows: 3 }"
            type="textarea"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button
        v-permission="['admin', 'task:edit']"
        :loading="doLoading"
        type="primary"
        @click="doComplete"
      >提交</el-button>
      <el-button
        v-if="
          $store.getters.user.username === 'admin' ||
            $store.getters.user.id + '' === startUserId + ''
        "
        v-permission="['admin', 'task:edit']"
        :loading="doLoading"
        type="primary"
        @click="doStop"
      >终止</el-button>
      <el-button
        v-if="!isInitiator"
        v-permission="['admin', 'task:edit']"
        :loading="doLoading"
        type="primary"
        @click="doAssign"
      >转办</el-button>
      <el-button
        v-if="!isInitiator"
        v-permission="['admin', 'task:edit']"
        :loading="doLoading"
        type="primary"
        @click="doDelegate"
      >委派</el-button>
      <el-button
        v-if="!isInitiator"
        v-permission="['admin', 'task:edit']"
        :loading="doLoading"
        type="primary"
        @click="doBack"
      >退回</el-button>
    </div>
    <select-user
      ref="selectUser"
      :visible.sync="selectUserVisible"
      :append-to-body="true"
      :multiple-select="false"
      @selectUserFinished="selectUserFinished"
    />
    <task-back-nodes
      v-if="dialogTaskBackNodesVisible"
      :visible.sync="dialogTaskBackNodesVisible"
      :execute-task-id="executeTaskId"
      @backTaskFinished="backTaskFinished"
    />
  </el-dialog>
</template>

<script>
import crud from '@/mixins/crud'
import selectUser from '@/components/UserSelect'
import taskBackNodes from '../components/TaskBackNodes'
import crudTask from '@/api/flowable/task'

export default {
  name: 'ExecuteTask',
  components: { selectUser, taskBackNodes },
  mixins: [crud],
  props: {
    visible: {
      type: Boolean,
      default: function() {
        return false
      }
    },
    executeTaskId: {
      type: String,
      default: function() {
        return ''
      }
    }
  },
  data() {
    return {
      doLoading: false,
      activeName: 'processInstanceForm',
      startUserId: '',
      showBusinessKey: false,
      businessKey: undefined,
      startFormKey: undefined,
      taskFormKey: undefined,
      isInitiator: false,
      startFormJson: undefined,
      processInstanceFormData: undefined,
      generateStartFormVisible: false,
      taskFormJson: undefined,
      taskFormData: undefined,
      generateTaskFormVisible: false,
      selectUserVisible: false,
      dialogTaskBackNodesVisible: false,
      message: ''
    }
  },
  computed: {
    dialogExcuteTaskVisibleInChild: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    beforeInit() {
      crudTask.execute(this.executeTaskId)
        .then((res) => {
          const data = res
          this.startUserId = data.startUserId
          this.showBusinessKey = data.showBusinessKey
          this.businessKey = data.businessKey
          this.startFormKey = data.startFormKey
          this.taskFormKey = data.taskFormKey
          this.isInitiator = data.isInitiator
          if (data.renderedStartForm) {
            this.startFormJson = JSON.parse(data.renderedStartForm)
            this.processInstanceFormData = JSON.parse(data.variables.processInstanceFormData)
            this.generateStartFormVisible = true
          }
          if (data.renderedTaskForm) {
            this.taskFormJson = JSON.parse(data.renderedTaskForm)
            if (this.startFormKey && this.taskFormKey && this.startFormKey === this.taskFormKey) {
              this.taskFormData = JSON.parse(data.variables.processInstanceFormData)
            }
            this.generateTaskFormVisible = true
          }
          if (this.generateTaskFormVisible) {
            this.activeName = 'taskForm'
          }
        })
        .catch(err => {
          console.log(err.response.data.message)
        })
    },
    doComplete() {
      this.checkMessage()
      if (this.$refs.generateFormTask) {
        this.$refs.generateFormTask.getData().then(values => {
          if (values && values !== undefined) {
            let realValues = values
            if (this.startFormKey && this.taskFormKey && this.startFormKey === this.taskFormKey) {
              const processInstanceFormData = JSON.stringify(values)
              realValues = Object.assign({ processInstanceFormData }, values)
            }
            crudTask.complete({
              id: this.executeTaskId,
              message: this.message,
              isInitiator: this.isInitiator,
              values: realValues
            }).then(res => {
              this.notify('提交成功', 'success')
              this.dialogExcuteTaskVisibleInChild = false
              this.$emit('executeTaskFinished')
            }).catch(err => {
              console.log(err.response.data.message)
            })
          }
        }).catch(err => {
          console.log(err.response.data.message)
        })
      } else {
        crudTask.complete({
          id: this.executeTaskId,
          message: this.message
        }).then(res => {
          this.notify('提交成功', 'success')
          this.dialogExcuteTaskVisibleInChild = false
          this.$emit('executeTaskFinished')
        }).catch(err => {
          console.log(err.response.data.message)
        })
      }
    },
    doStop() {
      this.checkMessage()
      crudTask.stop({
        id: this.executeTaskId,
        message: this.message
      }).then(res => {
        this.notify('终止成功', 'success')
        this.dialogExcuteTaskVisibleInChild = false
        this.$emit('executeTaskFinished')
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    doAssign() {
      this.checkMessage()
      this.selectUserVisible = true
      this.selectUserType = 'assign'
      // if (this.$refs.selectUser.treeData.length === 0) {
      //   this.$refs.selectUser.getTreeData()
      // }
    },
    doDelegate() {
      this.checkMessage()
      this.selectUserVisible = true
      this.selectUserType = 'delegate'
      // if (this.$refs.selectUser.treeData.length === 0) {
      //   this.$refs.selectUser.getTreeData()
      // }
    },
    doBack() {
      this.checkMessage()
      this.dialogTaskBackNodesVisible = true
    },
    selectUserFinished(selectData) {
      if (!selectData || selectData.length === 0) {
        this.$message.error('请先选择用户')
        return
      }
      if (this.selectUserType === 'assign') {
        crudTask.assign({
          id: this.executeTaskId,
          userId: selectData.id,
          message: this.message
        }).then(res => {
          this.notify('转办成功', 'success')
          this.selectUserVisible = false
          this.dialogExcuteTaskVisibleInChild = false
          this.$emit('executeTaskFinished')
        }).catch(err => {
          console.log(err.response.data.message)
        })
      } else if (this.selectUserType === 'delegate') {
        crudTask.delegate({
          id: this.executeTaskId,
          userId: selectData.id,
          message: this.message
        }).then(res => {
          this.notify('委派成功', 'success')
          this.selectUserVisible = false
          this.dialogExcuteTaskVisibleInChild = false
          this.$emit('executeTaskFinished')
        }).catch(err => {
          console.log(err.response.data.message)
        })
      }
    },
    backTaskFinished(backNode) {
      crudTask.back({
        id: this.executeTaskId,
        activityId: backNode.nodeId,
        activityName: backNode.nodeName,
        message: this.message
      }).then(res => {
        this.notify('退回成功', 'success')
        this.selectUserVisible = false
        this.dialogExcuteTaskVisibleInChild = false
        this.$emit('executeTaskFinished')
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    checkMessage() {
      if (!this.message || this.message === '') {
        this.$message.warning('请输入意见')
        return
      }
    }
  }
}
</script>
